import axios from 'axios'
import router from '@/router'

import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 25000 // request timeout
})

//  request 请求拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['Authorization'] = getToken()
      config.headers['Authorization'] = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response 响应拦截器
service.interceptors.response.use(

  response => {
    const res = response.data

    if (res.code === '0000') {
      return res
    } else if (res.code === '-3001' || res.code === '-3002') {
      alert(`您当前账户登录已失效,请您重新登录!`)
      router.push('/login')
      return res
    } else {
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })
      return res
    }
  },
  error => {
    Message({
      message: '网络断开或服务器错误!请检查网络链接状况并尝试刷新页面解决此问题',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
